<?php
// -----------------------------------------------------
// Created by : php-task
// -----------------------------------------------------
// User: tf <1096392101@qq.com>
// -----------------------------------------------------
declare (strict_types=1);

namespace Gao\Task\ipc;

//进程通信=>管道写入类
trait Pipe
{
    /**
     * @var string
     */
    protected $pipePath;

    /**
     * @var false|resource
     */
    private $w_pipe;

    /**
     * @var false|resource
     */
    private $r_pipe;

    public function __construct($name = 'pipe',$mode = 0666)
    {
        $pipePath = "/tmp/$name." . posix_getpid();

        if (!file_exists($pipePath)) {
            if (!posix_mkfifo($pipePath,$mode)) {
                exit("make pipe flase \n");
            }
        }

        $this->pipePath = $pipePath;
    }

    /**
     * 打开读文件
     */
    public function open_read(): bool
    {
        $this->r_pipe = fopen($this->pipePath,'r');
        if ($this->r_pipe == NULL) {
            //exit("open pipe {$this->fifoPath} for read error.");
            return false;
        }
        return true;
    }

    /**
     * 读取1024
     * @param int $byte
     * @return false|string
     */
    public function read($byte = 1024)
    {
        return fread($this->r_pipe,$byte);
    }

    /**
     * 读取全部
     * @return string
     */
    public function read_all(): string
    {
        $r_pipe = fopen($this->pipePath, 'r');
        $data = '';
        //没有到达尾部，继续读
        while (!feof($r_pipe)) {
            $data .= fread($r_pipe, 1024);
        }
        fclose($r_pipe);
        return $data;
    }

    /**
     * 打开写入文件
     */
    public function open_write(): bool
    {
        $this->w_pipe = fopen($this->pipePath,'w');
        if ($this->w_pipe == NULL) {
            return false;
        }
        return true;
    }

    /**
     * 写入
     * @param string $msg
     * @return false|int
     */
    public function write(string $msg)
    {
        return fwrite($this->w_pipe,$msg);
    }

    /**
     * @param $data
     */
    public function write_all($data)
    {
        $w_pipe = fopen($this->pipePath, 'w');
        fwrite($w_pipe, $data);
        fclose($w_pipe);
    }

    /**
     * @return bool
     */
    public function close_write(): bool
    {
        return fclose($this->w_pipe);
    }

    /**
     * 删除
     * @return bool
     */
    public function rm_file(): bool
    {
        return unlink($this->pipePath);
    }
}